package com.mengwen.backstage.service.impl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.mengwen.backstage.config.WeChatConfig;
import com.mengwen.backstage.mapper.WeChatUserInfoMapper;
import com.mengwen.backstage.pojo.WeixinUser;
import com.mengwen.backstage.service.UserInfoService;
import com.mengwen.backstage.util.GetLastAccessTokenUtil;
import com.mengwen.backstage.util.WeixinUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 微信服务号关注者服务层
 */
@Transactional
@Service
public class UserInfoServiceImpl implements UserInfoService{

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    private GetLastAccessTokenUtil getLastAccessTokenUtil;

    @Autowired
    WeChatConfig weChatConfig;

    @Autowired
    WeChatUserInfoMapper weChatUserInfoMapper;

//    private String USER_INFO_URL2 = weChatConfig.getWxOaGetUserInfoByOpenidAndAccessTokenUrl();
    private String USER_INFO_URL = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";

    public JSONObject getUserInfoAPI(String openId) throws Exception {
        String url = USER_INFO_URL.replace("ACCESS_TOKEN", getLastAccessTokenUtil.getAccessToken().getToken())
                .replace("OPENID",openId);
        return WeixinUtil.httpRequest(url, "GET", null);

    }


    /**
     * 将JSONObject转换成weixinuser对象
     */
    public WeixinUser JSONObjectToWeixinUser(JSONObject jsonObject) throws JsonProcessingException {
        System.out.println("有新关注者，增加用户信息：");
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.readValue(jsonObject.toString(), WeixinUser.class);
    }

    /**
     * 添加微信用户信息
     * @param weixinUser
     * @return
     */
    public int insertWeiXinUser(WeixinUser weixinUser){
        return weChatUserInfoMapper.addWeixinUser(weixinUser);
    }


    /**
     * 添加微信用户信息temp
     * @param openid
     * @throws Exception
     */
    public void addWeiXinUserInfo(String openid) throws Exception {
        JSONObject jsonObject = this.getUserInfoAPI(openid);
        WeixinUser weixinUser = this.JSONObjectToWeixinUser(jsonObject);
        this.insertWeiXinUser(weixinUser);
    }

    /**
     * 根据openid删除用户信息
     * @param fromUserName
     * @return
     */
    @Override
    public Integer deleteWeiXinUserInfo(String fromUserName) {
        return weChatUserInfoMapper.deleteByOpenid(fromUserName);
    }



}
